package com.converse.diamondreader.base;

import android.content.pm.PackageManager;
import android.os.Build;

import java.util.concurrent.atomic.AtomicBoolean;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Author: Leo Liao <lliao@midtronics.com>
 * Date: 02/12/2021 17:09
 * Description:
 */
public abstract class RequestPermissionActivity extends BasicUtilsActivity {
    private String[] permissions;
    private static final int PER_REQUEST_CODE = 111;
    private AtomicBoolean isFirstTimeResume = new AtomicBoolean(true);

    public String[] requestPermissions(){
        return new String[]{};
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isFirstTimeResume.compareAndSet(true, false)) {
            checkPermissions();
        }
    }

    protected void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissions = requestPermissions();
            boolean isAllGranted = true;
            if (permissions != null && permissions.length > 0) {
                for (String per : permissions) {
                    if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(per)) {
                        isAllGranted = false;
                        requestPermissions(permissions, PER_REQUEST_CODE);
                        break;
                    }
                }
            }
            if (isAllGranted) {
                onPermissionFulfilled(permissions);
            }
        }else {
            onPermissionFulfilled(permissions);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PER_REQUEST_CODE) {
            for (int result : grantResults) {
                if (PackageManager.PERMISSION_GRANTED != result) {
                    onBackPressed();
                    return;
                }
            }
        }

        onPermissionFulfilled(permissions);
    }

    protected void onPermissionFulfilled(String[] permissions){}
}
